package com.zch.house.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zch.house.dao.LogisticsDao;
import com.zch.house.entity.Logistics;
import com.zch.house.service.LogisticsService;
import com.zch.house.util.XmlSession;

public class LogisticsServiceImpl extends XmlSession implements LogisticsService {
	private final int PAGE_SIZE = 20;

	@Override
	public List<Logistics> getAllLogisticsByPage(String name, String phone, String sex, int pageIndex) {
		// 使用map集合来存放参数
		Map<String, Object> map = new HashMap<>();
		map.put("name", name);
		map.put("phone", phone);
		map.put("sex", sex);
		int firstRow = (pageIndex - 1) * PAGE_SIZE + 1;
		int lastRow = pageIndex * PAGE_SIZE;
		map.put("firstRow", firstRow);
		map.put("lastRow", lastRow);
		
		//加载配置文件
		initSession();
		//获得mapper的代理类
		LogisticsDao dao = session.getMapper(LogisticsDao.class);
		//调用dao层方法
		List<Logistics> list = dao.getAllLogistics(map);
		//提交事务并关闭session
		closeSession();
		return list;
	}

	@Override
	public int getTotalCount(String name, String phone, String sex) {
		// 使用map集合来存放参数
		Map<String, Object> map = new HashMap<>();
		map.put("name", name);
		map.put("phone", phone);
		map.put("sex", sex);
		
		//加载配置文件
		initSession();
		//获得mapper的代理类
		LogisticsDao dao = session.getMapper(LogisticsDao.class);
		// 调用dao层方法获得查询到的所有数据的个数
		int counts = dao.getTotalCount(map);
		//提交事务并关闭session
		closeSession();
		// 计算总页数
		int totalPages = counts % PAGE_SIZE == 0 ? counts / PAGE_SIZE : counts / PAGE_SIZE + 1;
		return totalPages;
	}

	@Override
	public Logistics getLogisticsById(int id) {
		//加载配置文件
		initSession();
		//获得mapper的代理类
		LogisticsDao dao = session.getMapper(LogisticsDao.class);
		// 调用dao层方法
		Logistics logistics = dao.getLogisticsById(id);
		//提交事务并关闭session
		closeSession();
		return logistics;
	}

	@Override
	public boolean addLogistics(Logistics logistics) {
		//加载配置文件
		initSession();
		//获得mapper的代理类
		LogisticsDao dao = session.getMapper(LogisticsDao.class);
		// 调用dao层方法
		boolean flag = dao.addLogistics(logistics);
		//提交事务并关闭session
		closeSession();
		return flag;
	}

	@Override
	public boolean deleteLogistics(int id) {
		Logistics logistics = getLogisticsById(id);
		logistics.setLo_status(0);
		boolean flag = updateLogistics(logistics);
		if(flag){
			return true;
		}
		return false;
	}

	@Override
	public boolean updateLogistics(Logistics logistics) {
		//加载配置文件
		initSession();
		//获得mapper的代理类
		LogisticsDao dao = session.getMapper(LogisticsDao.class);
		// 调用dao层方法
		boolean flag = dao.updateLogistics(logistics);
		//提交事务并关闭session
		closeSession();
		return flag;
	}

}
